
const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
  })
  
  const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    // 一、查出待开奖的抽奖
    let res = await db.collection('prize').aggregate()
    .match({
        status: 0
    })
    .end()
    let prizeList = res.list
    
    for(let prize of prizeList){
        // 判断开奖时间是否到了
        let date = new Date(prize.date).getTime()
        let now = new Date().getTime() + 1000 * 3600 * 8
     
        if(now < date){
            continue
        }
        // 判断这个抽奖是否被管制
        if(prize.control == 1){
            continue
        }


        // 二、在参与人列表中，选出一个中奖者
        res = await db.collection('prizeJoin').aggregate()
        .match({
            prizeId: prize._id
          })
        .sample({
            size: 1
        })
        .end()
       
        if(res.list.length == 0){
            continue
        }
        let winner = res.list[0]
        // 三、改变抽奖的状态，“待开奖” =》 “已开奖”
        await db.collection('prize').doc(prize._id).update({
            data: {
                status: 1
            }
          })
        // 四、将中奖人保存起来
        res = await db.collection('prizeWin').aggregate()
        .match({
            prizeId: prize._id
        })
        .end()
        if(res.list.length == 0){
            await db.collection('prizeWin').add({
                data: winner
            })
        
            await cloud.callFunction({
                name: 'sendMsg',
                data: {
                    type: 'openPrizeSend',
                    prizeId: prize._id
                }
            })
        }
        
    }

    return {
     
    }
}